package com.zzxx.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzxx.mapper.ProductMapper;
import com.zzxx.pojo.Product;
import com.zzxx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class ProductServiceImpl implements ProductService {
	@Autowired
	private ProductMapper productMapper;
	@Override
	public PageInfo<Product> findAll(int pageNum,int pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		List<Product> list = productMapper.findAll();
		PageInfo<Product> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@Override
	public boolean add(Product product){
		product.setId(UUID.randomUUID().toString().replace("-",""));

		correctProduct(product);

		try {
			productMapper.add(product);
			return true;
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean deleteById(List<String> list) {
		try {
			list.forEach(id -> productMapper.deleteById(id));
			return true;
		}catch (Exception e){
			return false;
		}
	}

	@Override
	public Product findById(String id) {
		return productMapper.findById(id);
	}

	@Override
	public boolean update(Product product) {
		correctProduct(product);
		try {
			productMapper.update(product);
			return true;
		}catch (Exception e){
			return false;
		}
	}

	@Override
	public boolean updateStatus(List<String> list, Integer state) {
		try {
			list.forEach(id->productMapper.updateStatusById(id,state));
			return true;
		}catch (Exception e){
			return false;
		}
	}

	private void correctProduct(Product product){
		if ("启用".equals(product.getProductStatusStr())){
			product.setProductStatus(1);
		}else{
			product.setProductStatus(0);
		}
		if ("".equals(product.getProductName())) product.setProductName(null);

		if ("".equals(product.getProductNum())) product.setProductNum(null);

		if ("".equals(product.getCityName())) product.setCityName(null);

		if ("".equals(product.getProductDesc())) product.setProductDesc(null);
	}
}
